package cn.lingyangwl.agile.system.service.impl;

import cn.lingyangwl.agile.system.assembly.ArticleGroupAssembly;
import cn.lingyangwl.agile.system.mapper.ArticleGroupMapper;
import cn.lingyangwl.agile.system.model.entity.ArticleGroup;
import cn.lingyangwl.agile.system.model.rqrs.article.ArticleGroupListReq;
import cn.lingyangwl.agile.system.model.rqrs.article.ArticleGroupResp;
import cn.lingyangwl.agile.system.model.rqrs.article.ArticleGroupSaveReq;
import cn.lingyangwl.agile.system.model.rqrs.article.ArticleGroupUpdateReq;
import cn.lingyangwl.agile.system.service.ArticleGroupService;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 文章组
 *
 * @author shenguangyang
 */
@Slf4j
@Service
public class ArticleGroupServiceImpl extends ServiceImpl<ArticleGroupMapper, ArticleGroup>
    implements IService<ArticleGroup>, ArticleGroupService {

    @Resource
    private ArticleGroupAssembly articleGroupAssembly;
    
    @Override
    public List<ArticleGroupResp> listGroup(ArticleGroupListReq req) {
        LambdaQueryWrapper<ArticleGroup> lqw = ArticleGroup.lqw()
                .like(StringUtils.isNotEmpty(req.getName()), ArticleGroup::getName, req.getName())
                .orderByAsc(ArticleGroup::getSortNo)
                .orderByDesc(ArticleGroup::getCreatedAt);
    	return this.list(lqw).stream()
    	        .map(articleGroupAssembly::toArticleGroupResp).collect(Collectors.toList());
    }

    @Override
    public ArticleGroupResp getGroup(Long id) {
        ArticleGroup entity = this.getById(id);
    	return articleGroupAssembly.toArticleGroupResp(entity);
    }

    @Override
    public boolean saveGroup(ArticleGroupSaveReq req) {
        ArticleGroup entity = articleGroupAssembly.toArticleGroup(req);
    	return this.save(entity);
    }

    @Override
    public boolean updateGroup(ArticleGroupUpdateReq req) {
        ArticleGroup entity = articleGroupAssembly.toArticleGroup(req);
    	return this.updateById(entity);
    }

    @Override
    public boolean deleteGroup(Long id) {
        ArticleGroup group = this.getById(id);
        if (Objects.nonNull(group) && group.getArticleNum() > 0) {
            throw new BizException("已有文章引用当前组");
        }
        return this.removeById(id);
    }
    
    @Override
    public boolean batchDeleteGroup(List<Long> ids) {
        boolean ret = listByIds(ids).stream().anyMatch(e -> e.getArticleNum() > 0);
        if (ret) {
            throw new BizException("已有文章引用当前组");
        }
    	return this.removeByIds(ids);
    }
}
